import axios from  'axios'
import {ElMessage} from "element-plus";

const request = axios.create({
    baseURL: '/',
    timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 1. 添加 token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        // 2. 设置 Content-Type (非必要，axios 会自动设置)
        if (!config.headers['Content-Type']) {
            config.headers['Content-Type'] = 'application/json;charset=utf-8'
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data

        // 假设后端返回 { code: 1,  {}, msg: '' }
        if (res.code === 1) {
            return res
        } else {
            // 业务错误
            ElMessage.error(res.msg || '操作失败')
            return Promise.reject(new Error(res.msg || 'Error'))
        }
    },
    error => {
        // HTTP 状态码错误处理
        console.log('err', error)
        let message = ''
        switch (error.response?.status) {
            case 401:
                message = '登录已过期，请重新登录'
                // 清除 token，跳转登录页
                localStorage.removeItem('token')
                window.location.href = '/login'
                break
            case 403:
                message = '没有权限访问'
                break
            case 404:
                message = '请求资源不存在'
                break
            default:
                message = error.message
        }
        ElMessage.error(message)
        return Promise.reject(error)
    }
)

export default request